package com.fablesoft.projectdatacollect.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.authentication.utils.ToastUtil;
import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.album.ImageItem;
import com.fablesoft.projectdatacollect.album.ShowAllPhotoActivity;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.FileMaterialBean;
import com.fablesoft.projectdatacollect.bean.ItemMaterial;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpUploadImagesThread;
import com.fablesoft.projectdatacollect.util.BitmapUtil;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.view.DividerGridItemDecoration;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FragmentMaterial extends BaseFragment {

    private RecyclerView rvMaterial;
    private Button btNext4;
    private Button btLast4;

    private FragmentMaterial.HomeAdapter adapter;
    private List<ItemMaterial> materials;
    private int currentPosition;
    private String[] materialNames;
    private int[] bgIds = {R.drawable.card_head, R.drawable.card_tail, R.drawable.certificate, R.drawable.icon_other};
    private static final int MAX_LENGTH = 12;
    int hasMaterial[] = new int[MAX_LENGTH];
    private List<String> deleteId;

    private DisplayImageOptions mOptions;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_material_photo, container, false);

        initView();
        initData();

        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        btNext4 = (Button) view.findViewById(R.id.next4);
        btLast4 = (Button) view.findViewById(R.id.last4);
        btNext4.setOnClickListener(this);
        btLast4.setOnClickListener(this);

        rvMaterial = (RecyclerView) view.findViewById(R.id.rv_material);
        rvMaterial.setLayoutManager(new GridLayoutManager(mContext, 4));
        rvMaterial.setAdapter(adapter = new HomeAdapter());
        rvMaterial.addItemDecoration(new DividerGridItemDecoration(mContext));
    }

    @Override
    protected void initData() {
        super.initData();
        if (mOptions == null) {
            mOptions = new DisplayImageOptions.Builder()
                    .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                    .resetViewBeforeLoading(true).cacheOnDisc(false)
                    .cacheInMemory(true)
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .considerExifParams(true).build();
        }
        if (materials == null) {
            materials = new ArrayList<>();
        }
        if (deleteId == null) {
            deleteId = new ArrayList<>();
        }
        for (int i = 0; i < MAX_LENGTH; i++) {
            hasMaterial[i] = i;
        }
        materialNames = getResources().getStringArray(R.array.material);

        ItemMaterial material;
        for (int i = 0; i < materialNames.length; i++) {
            material = new ItemMaterial(materialNames[i], bgIds[i]);
            materials.add(i, material);
        }

        int cur = 3;
        if (mActivity.result != null && mActivity.result.getData() != null && mActivity.result.getData().getOrgPersonFileList() != null) {
            Log.d(CommonUtils.TAG_UPLOAD, "OrgPersonFileList size = " + mActivity.result.getData().getOrgPersonFileList().size());
            for (FileMaterialBean fileBean : mActivity.result.getData().getOrgPersonFileList()) {
                ItemMaterial item = fileBean.getFileBean();
                if (!TextUtils.isEmpty(item.getFilePath())) {
                    if (cur >= MAX_LENGTH) {
                        break;
                    }
                    if (item.getFileName().contains(materialNames[0])) {
                        item.setItemName(materialNames[0]);
                        item.setBackground(bgIds[0]);
                        materials.remove(0);
                        materials.add(0, item);
                        add(0);
                    } else if (item.getFileName().contains(materialNames[1])) {
                        item.setItemName(materialNames[1]);
                        item.setBackground(bgIds[1]);
                        materials.remove(1);
                        materials.add(1, item);
                        add(1);
                    } else if (item.getFileName().contains(materialNames[2])) {
                        item.setItemName(materialNames[2]);
                        item.setBackground(bgIds[2]);
                        materials.remove(2);
                        materials.add(2, item);
                        add(2);
                    } else if (item.getFileName().contains(materialNames[3])) {
                        item.setItemName(materialNames[3]);
                        item.setBackground(bgIds[3]);
                        if (cur <= 3) {
                            materials.remove(cur);
                            materials.add(cur, item);
                        } else {
                            materials.add(item);
                        }
                        add(cur++);
                    }
                }
            }
            if (cur > 3) {
                ItemMaterial materialOther = new ItemMaterial(materialNames[materialNames.length - 1], bgIds[bgIds.length - 1]);
                materials.add(materialOther);
            }
        }
        adapter.notifyDataSetChanged();
    }

    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {

        @Override
        public HomeAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            HomeAdapter.MyViewHolder holder = new HomeAdapter.MyViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_material, parent,
                    false));
            return holder;
        }

        @Override
        public void onBindViewHolder(HomeAdapter.MyViewHolder holder, final int position) {
            final ItemMaterial material = materials.get(position);
            holder.tv.setText(material.getItemName());
            holder.iv.setImageResource(material.getBackground());

            if (!TextUtils.isEmpty(material.getFilePath())) {
                String url = Config.BASE + material.getFilePath();
                url = url.replaceAll("\\\\", "/");
                Log.d(CommonUtils.TAG_UPLOAD, "material path = " + url);
                ImageLoader.getInstance().displayImage(url, holder.iv, mOptions);
                holder.x.setVisibility(View.VISIBLE);
            } else if (material.getThumbBitmap() != null) {
                holder.iv.setImageBitmap(material.getThumbBitmap());
                holder.x.setVisibility(View.VISIBLE);
            } else {
                holder.iv.setImageResource(bgIds[position < 3 ? position : bgIds.length - 1]);
                holder.x.setVisibility(View.GONE);
            }

            holder.iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext,
                            ShowAllPhotoActivity.class);
                    intent.putExtra("count", 1);
                    currentPosition = position;
                    startActivityForResult(intent, CommonUtils.IMAGE_OPEN);
                }
            });
            holder.x.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    ItemMaterial newMaterial = new ItemMaterial(material.getItemName());
                    materials.remove(material);
                    if (!TextUtils.isEmpty(material.getId())) {
                        deleteId.add(material.getId());
                    }
                    delete(position);
                    currentPosition = getCurrentPostion();
                    materials.add(position, newMaterial);
                    notifyDataSetChanged();
                }
            });
        }

        @Override
        public int getItemCount() {
            return materials.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tv;
            ImageView iv;
            ImageView x;

            public MyViewHolder(View view) {
                super(view);
                tv = (TextView) view.findViewById(R.id.tv_item_mertrial);
                iv = (ImageView) view.findViewById(R.id.iv_item_material);
                x = (ImageView) view.findViewById(R.id.iv_item_delete);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (isRepeatClick(v)) {
            return;
        }
        switch (v.getId()) {
            case R.id.next4:
                listener.onNext(4);
                break;
            case R.id.last4:
                listener.onLast(4);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == CommonUtils.IMAGE_OPEN) {
            if (ShowAllPhotoActivity.tempSelectBitmap == null || ShowAllPhotoActivity.tempSelectBitmap.size() <= 0) {
                ToastUtil.showToast(mContext, "请选择图片！");
                return;
            }
            ImageItem item = ShowAllPhotoActivity.tempSelectBitmap.get(0);
            showMaterialImage(item.getImagePath());
        }
    }

    private void showMaterialImage(String imagePath) {
        if (currentPosition >= MAX_LENGTH) {
            return;
        }
        String filename = "";
        ItemMaterial material = new ItemMaterial();
        if (currentPosition < 3) {
            filename = materialNames[currentPosition];
        } else {
            filename = materialNames[materialNames.length - 1];
            ItemMaterial materialOther = new ItemMaterial(filename, bgIds[bgIds.length - 1]);
            materials.add(materialOther);
        }
        material.setFileName(filename);
        material.setThumbBitmap(BitmapUtil.decodeThumbBitmapForFile(imagePath, 125, 104));
        material.setLocalPath(imagePath);
        material.setItemName(filename);
        materials.remove(currentPosition);
        materials.add(currentPosition, material);
        add(currentPosition);
        currentPosition = getCurrentPostion();
        adapter.notifyDataSetChanged();
    }

    private void add(int position) {
        for (int i = 0; i < hasMaterial.length; i++) {
            if (position == hasMaterial[i]) {
                hasMaterial[i] = -1;
                break;
            }
        }
    }

    private void delete(int position) {
        for (int i = 0; i < hasMaterial.length; i++) {
            if (-1 == hasMaterial[i]) {
                hasMaterial[i] = position;
                break;
            }
        }
        Arrays.sort(hasMaterial);
    }

    private int getCurrentPostion() {
        for (int i = 0; i < hasMaterial.length; i++) {
            if (-1 != hasMaterial[i]) {
                return hasMaterial[i];
            }
        }
        return hasMaterial.length + 1;
    }

    public void submitMaterials() {
        List<ItemMaterial> submitMaterials = new ArrayList<>();
        for (ItemMaterial item : materials) {
            if (!TextUtils.isEmpty(item.getLocalPath())) {
                item.setFileName(item.getFileName());
                submitMaterials.add(item);
            }
        }
        if (submitMaterials.size() <= 0) {
            Log.d(CommonUtils.TAG_UPLOAD, "没有材料图片，无法上传！");
            listener.onSubmitStatus(CommonUtils.UPLOAD_CERTIFICATER_IMAGE, true, false);
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("cardId", mActivity.idNo);
        params.put("id", mActivity.baseInfo.getId());
        params.put("deleteFileIds", CommonUtils.listToString(deleteId));
        Log.d(CommonUtils.TAG_UPLOAD, "材料图片开始上传......params = " + params);
        HttpUploadImagesThread thread = new HttpUploadImagesThread(Config.UPLOAD_MATERIAL_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = CommonUtils.UPLOAD_CERTIFICATER_IMAGE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                        mActivity.onNotLogin(response);
                    }
                }, submitMaterials, params, BaseResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(thread);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CommonUtils.UPLOAD_CERTIFICATER_IMAGE:
                    BaseResponse materialResponse = (BaseResponse) msg.obj;
                    if (materialResponse == null) {
                        listener.onSubmitStatus(CommonUtils.UPLOAD_CERTIFICATER_IMAGE, false, true);
                        return;
                    }
                    listener.onSubmitStatus(CommonUtils.UPLOAD_CERTIFICATER_IMAGE, true, false);
                    break;
            }
        }
    };


}
